/**
 * This file is part of the dspace-poltman project http://www.poltman.com.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of DuraSpace DSpace license detailed in the LICENSE and NOTICE 
 * files at the root of the source tree and available online at
 * http://www.dspace.org/license/
 * 
 */

package com.poltman.dscentral.communities;

import java.util.Set;

import org.apache.log4j.Logger;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.AbstractTreeModel;
import org.zkoss.zul.Treecell;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.TreeitemRenderer;
import org.zkoss.zul.Treerow;

import com.poltman.dscentral.db.entity.dspace.CommunityEntity;
import com.poltman.dscentral.db.service.dspace.CommunityService;
import com.poltman.dscentral.core.CoreSessionData;
import com.poltman.dscentral.core.dspace.Communities;

/**
 * 
 * @author z.ciok@poltman.com
 *
 */

@SuppressWarnings("rawtypes")
public class NewTopLevelCommunityTreeRenderer implements TreeitemRenderer {
	
	private static Logger log = Logger.getLogger(NewTopLevelCommunityTreeRenderer.class);
	
	Communities communities;
	
	/**
	 * 
	 * @param communities
	 */
	public NewTopLevelCommunityTreeRenderer(Communities communities) {
		this.communities = communities;
	}	

	/**
	 * 
	 */
    public void render(Treeitem item, Object data, int index) throws Exception {
    	
        CommunityService  communityService = (CommunityService) SpringUtil.getBean("communityService");
        final CommunityEntity community = communityService.findByCommunityId(((Integer) data));
        Treerow treeRow = new Treerow();
        
        saveDataForTreeRefresh();
        
        item.addEventListener("onOpen", new EventListener<Event>() {
            @Override
            public void onEvent(Event event) throws Exception {
            	saveDataForTreeRefresh();
            }
        });
        item.appendChild(treeRow);
        treeRow.appendChild(new Treecell(community.getName()));
    }

    /**
     * 
     */
    private void saveDataForTreeRefresh() {
    	CoreSessionData coreSessionData = (CoreSessionData) SpringUtil.getBean("coreSessionData");
    	coreSessionData.setAttribute("NewTopLevelCommunities", communities);
    	
    	AbstractTreeModel ctm = (AbstractTreeModel)(communities.getTree().getModel());
    	@SuppressWarnings("unchecked")
		Set<Integer> opened = ctm.getOpenObjects();
    	coreSessionData.setAttribute("NewTopLevelCommunityOpenedTreeObjects", opened);
    }
}
